package com.djl.zenithbite.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailUtil {
    private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);

    @Autowired
    private JavaMailSender sender;//得到发送邮件的对象

    @Value("${spring.mail.username}")
    private String from;//得到发件人

    public void send(String to, String subject, String content) {

        try {
            //发送邮件实体
            MimeMessage mimeMessage = sender.createMimeMessage();
            //包装类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            //设置发件人
            helper.setFrom(from);
            //设置收件人
            helper.setTo(to);
            //设置邮件注册
            helper.setSubject(subject);
            //设置邮件内容，true代表支持html
            helper.setText(content, true);
            sender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("send mail failed :" + e.getMessage());
        }
    }
}
